let express = require('express');
let Class = require('../models/class');
let router = express.Router();

router.get('/' , (req , res) => {
  res.render("index");
});

//获取分类
router.get('/getClass' , (req , res) => {
  let data = {};
  if(req.body.id){
    data = {
      _id:req.body.id
    };
  };
  Class.get(data , (error , data) => {
    if(error){
      res.json({
        state:'error',
        message:'分类获取失败'
      })
    }else{
      res.json({
        state:'ok',
        message:'分类获取成功',
        data:data
      });
    };
  })
});

//添加分类
router.post('/addClass' , (req , res) => {
  let data = req.body;
  data = {
    name:data.name,
    pubdate:new Date().getTime()
  };
  if(!data.name){
    res.json({
      state:'error',
      message:'分类名称不能为空'
    });
  }else{
    Class.add(data , (error , data) => {
      if(error){
        res.json({
          state:'error',
          message:'添加失败'
        });
      }else{
        res.json({
          state:'ok',
          message:'添加成功',
          data:data
        });
      };
    })
  };
})

//删除分类
router.post('/delClass' , (req , res) => {
  if(req.body.id){
    let id = {_id:req.body.id};
    Class.remove(id , (error , data) => {
      if(error){
        res.json({
          state:'error',
          message:'删除失败'
        });
      }else{
        res.json({
          state:'ok',
          message:'删除成功'
        });
      };
    });
  }else{
    res.json({
      state:'error',
      message:'请选择要删除的分类'
    });
  };
});

//delall
router.get('/delall' , (req , res) => {
  Class.remove({name:'新建文件夹'} , (error , data) => {
    console.log(error || data);
  })
})
module.exports = router;
